package com.cuitrip.business.tripservice.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;

import com.cuitrip.apiservice.CommonBusiness;
import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.trip.TripServiceListFragment;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.tripservice.CreateServiceSuccessActivity;
import com.cuitrip.business.tripservice.EditTripHighLightActivity;
import com.cuitrip.business.tripservice.EditTripTagsActivity;
import com.cuitrip.business.tripservice.ParaEditActivity;
import com.cuitrip.business.tripservice.ServiceDetailActivity;
import com.cuitrip.business.tripservice.TripDemandInstructionActivity;
import com.cuitrip.business.tripservice.TripDescriptionActivity;
import com.cuitrip.business.tripservice.TripEditActivity;
import com.cuitrip.business.tripservice.TripOtherInstructionActivity;
import com.cuitrip.business.tripservice.TripPayInstructionFragment;
import com.cuitrip.business.tripservice.model.CategoryInfo;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.proxy.ServiceFormProxy;
import com.cuitrip.business.tripservice.ui.TripEditView;
import com.cuitrip.business.user.ChooseCityActivity;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.component.choicedialog.MultiItem;
import com.cuitrip.component.para.proxy.ParaProxy;
import com.cuitrip.service.R;
import com.cuitrip.util.ImageFetcherManager;
import com.cuitrip.util.MediaFetcher;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.BaseActivity;
import com.lab.app.BaseFragment;
import com.lab.logtrack.AppLog;
import com.lab.mvp.presenter.Presenter;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.photopicker.DefaultCallback;
import com.lab.photopicker.EasyImage;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.MessageUtils;
import com.lab.utils.imageupload.imp.OssService;
import com.lab.utils.imageupload.model.OssTokenObject;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 行程编辑页面presenter
 * Created by ak
 */
public class TripEditPresenter implements Presenter<TripEditView>, IProxyCallback{

    public static final String SERVICE_INFO_KEY = "service_info";

    public static final int PREVIEW_ACTION = 0x01;
    public static final int DRAFT_ACTION = 0x02;
    public static final int COMMIT_ACTION = 0x03;
    public static final int TITLE_TYPE = 0x01;
    public static final int LOCATION_TYPE = 0x02;
    public static final int HIGHLIGHT_TYPE = 0x03;
    public static final int DESCRIPTION_TYPE = 0x04;
    public static final int OTHER_INSTRUCTION_TYPE = 0x05;
    public static final int DEMAND_INSTRUCTION_TYPE = 0x06;
    public static final int PAY_INSTRUCTION_TYPE = 0x07;


    private TripEditView mTripEditView;

    private ServiceInfo mServiceInfo;

    private int mSaveAction;

    private File tempPhotoFile;

    private ApiProxy mApiProxy = new ApiProxy(this);
    private OssService mOssService = new OssService();

    private ImageFetcherManager mImageFetcherManager;

    @Override
    public void attachView(TripEditView view) {
        mTripEditView = view;
        mImageFetcherManager = new ImageFetcherManager((BaseActivity) view.getContext(), ImageFetcherManager.Source.CREATE_SERVICE);
    }

    public ServiceInfo initServiceInfo(ServiceInfo serviceInfo, TripEditActivity.ContentMode contentMode){
        mServiceInfo = serviceInfo;
        if (mServiceInfo == null){
            mServiceInfo = new ServiceInfo();
        }
        mServiceInfo.setEditMode(contentMode);
        return mServiceInfo;
    }

    public void renderUi(){
        mTripEditView.renderTitle(mServiceInfo);
        mTripEditView.renderLocation(mServiceInfo);
        renderHighLight();
        mTripEditView.renderDescription(mServiceInfo);
        mTripEditView.renderMainPic(mServiceInfo);
        mTripEditView.renderOtherNotes(mServiceInfo);
        mTripEditView.renderDemands(mServiceInfo);
        renderPayInstruction();
    }

    public void navigateToSelectCity(BaseFragment fragment){
        ChooseCityActivity.chooseLocation(fragment, ChooseCityActivity.SERVICE_MODE);
    }

    public void navigateToHighLight(BaseActivity activity, Fragment fragment){
        Intent intent = new Intent(activity, EditTripHighLightActivity.class);
        intent.putExtra(ParaEditActivity.TITLE_KEY, ResourceUtil.getString(R.string.trip_attribute_highlight));
        intent.putExtra(SERVICE_INFO_KEY, mServiceInfo);
        if (!TextUtils.isEmpty(mServiceInfo.getHighLight())) {
            intent.putExtra(ParaEditActivity.PARA_KEY, ParaProxy.getInstance().getParaList(mServiceInfo.getHighLight()));
        }
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/highlights");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/highlights");
        }
        fragment.startActivityForResult(intent, HIGHLIGHT_TYPE);
    }

    public void navigateToDescription(BaseActivity activity, Fragment fragment){
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/description");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/description");
        }
        Intent intent = new Intent(activity, TripDescriptionActivity.class);
        if (!TextUtils.isEmpty(mServiceInfo.getServiceDescript())) {
            intent.putExtra(ServiceInfo.KEY, mServiceInfo)
                    .putExtra(TripDescriptionActivity.EDIT_MODE, true);
        }
        fragment.startActivityForResult(intent, DESCRIPTION_TYPE);
    }

    public void navigateOtherInstruction(BaseActivity activity, Fragment fragment){
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/additional");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/additional");
        }
        mServiceInfo.otherNotes.setContentMode(mServiceInfo.getEditMode());
        Intent intent = TripOtherInstructionActivity.getOtherNotesIntent(activity, mServiceInfo.getOtherNotes(),true);
        fragment.startActivityForResult(intent, OTHER_INSTRUCTION_TYPE);
    }

    public void navigate2Demand(BaseActivity activity, Fragment fragment){
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/booking");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/booking");
        }

        Intent intent = new Intent(activity, TripDemandInstructionActivity.class);
        intent.putExtra(SERVICE_INFO_KEY, mServiceInfo);
        fragment.startActivityForResult(intent, DEMAND_INSTRUCTION_TYPE);
    }



    public void navigateToPayInstruction(BaseActivity activity){
        if (mServiceInfo.getEditMode().ordinal() == TripEditActivity.ContentMode.NEW_MODE.ordinal()){
            TrackUtil.trackScreenName("/insider/trips/create/set/price");
        }else{
            TrackUtil.trackScreenName("/insider/trips/edit/set/price");
        }
        TripPayInstructionFragment tripPayInstructionFragment = new TripPayInstructionFragment();
        tripPayInstructionFragment.setTripMainUpdater(this);
        Bundle bundle = new Bundle();
        bundle.putSerializable(ServiceInfo.KEY, mServiceInfo);
        tripPayInstructionFragment.setArguments(bundle);
        activity.openFragment(tripPayInstructionFragment, R.id.container, TripPayInstructionFragment.class.getName(), true);
    }

    public void commitTrip(String title){
        mServiceInfo.setName(title);
        ServiceFormProxy.InValidType inValidType = ServiceFormProxy.getInstance().isFormComplete(mServiceInfo);
        boolean isValid = mTripEditView.performInvalidAction(inValidType);
        if (!isValid) {
            return;
        }
        mTripEditView.showLoadingDialog();
        mServiceInfo.setOnlineState(ServiceInfo.ONLINE_STATE);
        mSaveAction = COMMIT_ACTION;
        ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
    }

    public void preview(String title) {
        mServiceInfo.setName(title);
        ServiceFormProxy.InValidType inValidType = ServiceFormProxy.getInstance().isFormComplete(mServiceInfo);
        boolean isValid = mTripEditView.performInvalidAction(inValidType);
        if (!isValid) {
            return;
        }
        mServiceInfo.setOnlineState(ServiceInfo.DRAFT_STATE);
        mSaveAction = PREVIEW_ACTION;
        ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);
    }

    public void onLeftPage(final String title){
        String[] tip;
        if (mServiceInfo.isUnSync()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_as_draft), ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else if (mServiceInfo.isChecked()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else if (mServiceInfo.isCheckFailed()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_as_draft), ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else if (mServiceInfo.isDraft()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_as_draft), ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else if (mServiceInfo.isChecking()) {
            tip = new String[]{ResourceUtil.getString(R.string.operation_save_as_draft), ResourceUtil.getString(R.string.operation_save_no), ResourceUtil.getString(R.string.operation_cancel)};
        } else {
            return;
        }

        final ChoiceDialog choiceDialog = ChoiceDialog.getInstance();
        List<MultiItem> multiItemList = new ArrayList<MultiItem>();
        for (String apiString : tip) {
            MultiItem multiItem = new MultiItem(apiString);
            if (apiString.equals(ResourceUtil.getString(R.string.operation_save_as_draft))){
                multiItem.setColor(ResourceUtil.getThemeColor());
            }else{
                multiItem.setColor(ResourceUtil.getColor(R.color.qiaomai_7c706e));
            }
            multiItemList.add(multiItem);
        }
        choiceDialog.setDialogMessageVisibility(false);
        choiceDialog.setDialogTitleVisibility(false);
        choiceDialog.setDialogMultiStyleSetting(multiItemList, new ChoiceDialog.DialogStyleMultiCallback() {
            @Override
            public boolean onMultiItemClick(MultiItem multiItem, int position) {
                if (position == 0) {
                    if (mServiceInfo.isUnSync() || mServiceInfo.isCheckFailed() || mServiceInfo.isDraft()|| mServiceInfo.isChecking()) {
                        mServiceInfo.setName(title);
                        if (TextUtils.isEmpty(mServiceInfo.getName())) {
                            mTripEditView.performInvalidAction(ServiceFormProxy.InValidType.TITLE);
                        } else {
                            mTripEditView.showLoadingDialog();
                            mServiceInfo.setOnlineState(ServiceInfo.DRAFT_STATE);
                            mSaveAction = DRAFT_ACTION;
                            ServiceBusiness.commitServiceInfo(mApiProxy, mServiceInfo);

                        }
                    } else {
                        mTripEditView.finishPage();
                    }
                } else if (position == 1) {
                    if (mServiceInfo.isUnSync() || mServiceInfo.isCheckFailed() || mServiceInfo.isDraft()||mServiceInfo.isChecking()) {
                        mTripEditView.finishPage();
                    }

                }
                choiceDialog.dismiss();
                return true;
            }
        });
        mTripEditView.showDialogFragment(choiceDialog);
    }


    public boolean handleActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode== ChooseCityActivity.REQUEST_CHOOSE_LOCATION) {
            if (resultCode== Activity.RESULT_OK){
                String countryName = data.getStringExtra(ChooseCityActivity.COUNTRY_NAME_KEY);
                String countryAbbr = data.getStringExtra(ChooseCityActivity.COUNTRY_ABBR_KEY);
                String cityAbbr = data.getStringExtra(ChooseCityActivity.CITY_ABBR_KEY);
                String city=data.getStringExtra(ChooseCityActivity.CITY_NAME_KEY);
                String address = data.getStringExtra(ChooseCityActivity.ADDRESS_KEY);
                mServiceInfo.setAddress(address);
                mServiceInfo.setCountry(countryAbbr);
                mServiceInfo.setCity(city);
                mServiceInfo.setCityAbbr(cityAbbr);
                mTripEditView.renderLocation(mServiceInfo);
                return true;
            }
        }else if (requestCode == HIGHLIGHT_TYPE) {
            if (resultCode == Activity.RESULT_OK) {
                List<CharSequence> highList = data.getCharSequenceArrayListExtra(ParaEditActivity.PARA_KEY);
                List<CategoryInfo> categoryInfoList = data.getParcelableArrayListExtra(EditTripTagsActivity.TAG_KEY);
                mServiceInfo.setHighLight(ParaProxy.getInstance().outputPara(highList));
                mServiceInfo.setCateList(categoryInfoList);
                renderHighLight();
                return true;
            }
        }else if (requestCode == DESCRIPTION_TYPE) {
            if (resultCode == Activity.RESULT_OK){
                mServiceInfo.setPic(data.getStringArrayListExtra(TripDescriptionActivity.PIC_LIST_KEY));
                mServiceInfo.setServiceDescript(data.getStringExtra(TripDescriptionActivity.DESC_KEY));
                mTripEditView.renderDescription(mServiceInfo);
                return true;
            }
        }else if (requestCode == OTHER_INSTRUCTION_TYPE) {
            if (resultCode == Activity.RESULT_OK) {
                //java 的数据结构，咳咳，看看有没有更好的方式
                List<CharSequence> safeTips = data.getCharSequenceArrayListExtra(TripOtherInstructionActivity.SAFE_KEY);
                mServiceInfo.otherNotes.setServiceSafeTips(ParaProxy.getInstance().outputPara(safeTips));

                List<CharSequence> attentionTips = data.getCharSequenceArrayListExtra(TripOtherInstructionActivity.ATTENTION_KEY);
                mServiceInfo.otherNotes.setServiceNotice(ParaProxy.getInstance().outputPara(attentionTips));

                List<CharSequence> clothTips = data.getCharSequenceArrayListExtra(TripOtherInstructionActivity.CLOTH_KEY);
                mServiceInfo.otherNotes.setServiceWearTips(ParaProxy.getInstance().outputPara(clothTips));

                List<CharSequence> weatherTips = data.getCharSequenceArrayListExtra(TripOtherInstructionActivity.WEATHER_KEY);
                mServiceInfo.otherNotes.setUnexpectedWeather(ParaProxy.getInstance().outputPara(weatherTips));
                mTripEditView.renderOtherNotes(mServiceInfo);
            }
        } else if (requestCode == DEMAND_INSTRUCTION_TYPE) {
            mServiceInfo.setMeetingPlace(data.getStringExtra(TripDemandInstructionActivity.MEETINGPLACE_KEY));
            mServiceInfo.setLat(data.getStringExtra(TripDemandInstructionActivity.LATITUDE_KEY));
            mServiceInfo.setLng(data.getStringExtra(TripDemandInstructionActivity.LONGTITUDE_KEY));
            mServiceInfo.setServiceTime(data.getStringExtra(TripDemandInstructionActivity.DURATION_KEY));
            mServiceInfo.setBestTime(data.getStringExtra(TripDemandInstructionActivity.BESTTIME_KEY));
            mServiceInfo.setMinBuyerNum(data.getIntExtra(TripDemandInstructionActivity.PERSON_MIN_KEY, 0));
            mServiceInfo.setMaxbuyerNum(data.getIntExtra(TripDemandInstructionActivity.PERSON_MAX_KEY, 0));
            mServiceInfo.setPreOrderDays(data.getIntExtra(TripDemandInstructionActivity.ADVANCE_DAY_KEY, 1));
            mTripEditView.renderDemands(mServiceInfo);
        }

        EasyImage.handleActivityResult(requestCode, resultCode, data, mTripEditView.getContext(), new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
                //Some error handling
            }

            @Override
            public void onImagePicked(final File imageFile, EasyImage.ImageSource source) {
                //Handle the image
                if (null != imageFile && !TextUtils.isEmpty(imageFile.getAbsolutePath())) {
                    ImageLoader.getInstance().loadImage(Uri.fromFile(imageFile).toString(), new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
                            mTripEditView.renderMainPic(loadedImage);
                        }
                    });
                    tempPhotoFile = imageFile;
                    uploadImage();
                }

            }

            @Override
            public void onCanceled(EasyImage.ImageSource source) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(AppCoreRuntime.context);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
        return false;
    }

    private void uploadImage() {
        mTripEditView.showLoadingDialog();
        CommonBusiness.getMobileOssToken(mApiProxy);
    }

    public void chooseMainImagePic(Fragment fragment) {
        tempPhotoFile =
                MediaFetcher.getTempImageFilePath(AppCoreRuntime.context);
        if (tempPhotoFile == null) {
            return;
        }
        EasyImage.openChooser(fragment, "", true);
    }


    public void renderPayInstruction(){
        mTripEditView.renderPayInfo(mServiceInfo);
    }

    public void renderHighLight(){
        mTripEditView.renderHighLight(mServiceInfo);
    }


    @Override
    public void detachView() {
        this.mTripEditView = null;
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {

        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.GET_MOBILE_OSS_TOKEN.equals(response.getApiName())) {
            if (response.isResponseNormal()) {
                if (response.result instanceof OssTokenObject) {
                    OssTokenObject ossTokenObject = (OssTokenObject) response.result;
                    mOssService.initClient(ossTokenObject);
                    mOssService.asyncPutImage(OssService.getObjectName(LoginInstance.getInstance().getUserInfo().getUid(), tempPhotoFile), tempPhotoFile.getAbsolutePath(), new OssService.UploadCallback() {
                        @Override
                        public void onFailure(String errorMessage) {
                            mTripEditView.hideLoadingDialog();
                        }

                        @Override
                        public void onSuccess(String url) {
                            mTripEditView.hideLoadingDialog();
                            mServiceInfo.setBackPic(url);
                            mTripEditView.renderMainPic(mServiceInfo);
                        }

                        @Override
                        public void onProgress(int progress) {
                            AppLog.d("progress" + progress);
                        }
                    });

                }
            } else {
                mTripEditView.hideLoadingDialog();
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }

        } else if (ApiManager.SERVICE_COMMIT.equals(response.getApiName())) {
            mTripEditView.hideLoadingDialog();
            if (response.isResponseNormal()) {
                if (response.result instanceof ServiceInfo) {
                    ServiceInfo serviceInfo = (ServiceInfo) response.result;
                    mServiceInfo.setSid(serviceInfo.getSid());
                    handleSuccessResult(serviceInfo);
                }
            } else {
                if (!TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }
        }
        return false;
    }

    private void handleSuccessResult(ServiceInfo serviceInfo){
        Context context = mTripEditView.getContext();
        if (context == null){
            return;
        }
        LocalBroadcastManager.getInstance(AppCoreRuntime.context).sendBroadcast(
                new Intent(TripServiceListFragment.TRIP_SERVICE_STATUS_CHANGED));
        if (mSaveAction == COMMIT_ACTION){
            context.startActivity(new Intent(context, CreateServiceSuccessActivity.class));
            mTripEditView.finishPage();
        }else if (mSaveAction == DRAFT_ACTION){
            mTripEditView.finishPage();
        }else if (mSaveAction == PREVIEW_ACTION){
            TrackUtil.trackScreenName("/insider/trips/preview");
            ServiceDetailActivity.startFinder(context, serviceInfo.getSid(), ServiceInfo.STATUS_DRAFT);
        }

    }


}
